package tech.aistar.clothesspringboot.intercepter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.aistar.clothesspringboot.utils.JwtUtils;


@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录拦截器");
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(403);
            return false;
        }
        try{
            Claims claims = JwtUtils.verifyToken(token);
            Integer userId = claims.get("id", Integer.class);
            request.setAttribute("userId",userId);
        }catch (Exception e){
            response.setStatus(403);
            return false;
        }
        return true;
    }

}
